<template>
  <div>
    <!-- 搜索 -->
    <van-nav-bar>
      <!-- <van-nav-bar fixed placeholder> -->
      <template #title>
        <router-link class="home-header-search" to="/search">
          <van-icon name="search" /><span>搜索</span>
        </router-link>
      </template>
    </van-nav-bar>

    <!-- 导航 -->
    <div class="nav">
      <van-tabs v-model="active" @click="switchTab">
        <van-tab :title="item.name" v-for="item in cate" :key="item.id">
        </van-tab>
      </van-tabs>
    </div>

    <div class="home">
      <!-- 下拉刷新 -->
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <!-- 下拉提示，通过 scale 实现一个缩放效果 -->

        <!-- 释放提示 -->
        <template #loosing>
          <img class="doge" src="https://img01.yzcdn.cn/vant/doge.png" />
        </template>
        <!-- 加载提示 -->
        <template #loading>
          <img class="doge" src="https://img01.yzcdn.cn/vant/doge-fire.jpg" />
        </template>

        <div class="main" style="padding-bottom: 60px">
          <!-- 内容 -->
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="我也是有底线的，请不要挑战我的底线"
            @load="getArticle"
            :immediate-check="false"
          >
            <!-- 加载小图标 -->

            <!-- @load="getArticle" 初始化完成后会自动触发一次 -->
            <!-- <template #finished>
          <div style="text-align: center; padding: 10px">
            <van-icon name="clock-o" size="30" color="red"></van-icon>
          </div>
          </template>

          <template #loading>
            <div style="text-align: center; padding: 10px">
              <van-icon name="clock-o" size="30" color="red"></van-icon>
            </div>
          </template> -->

            <li
            class="main-article"
              v-for="item in articleList"
              :key="item._id"
              @click="
                $router.push({
                  path: '/article',
                  query: { id: item._id, title: item.title },
                })
              "
            >
            <!-- 标题 -->
              <p class="title_hover" :title="item.title">
                标题：{{ item.title }}
              </p>
              <!-- 图片 -->
              <div
              class="main-image"
                :class="{
                  none: item.poster_type == 1,
                  articlesingleImg: item.porster_type == 2,
                  articlemoreImg: item.porster_type == 3,
                }"
              >
                <img v-for="img in item.imageSrc" v-lazy="img" />
              </div>
              <!-- 评论日期 -->
              <p>评论日期：{{ item.time | timeFilter }}</p>
            </li>
          </van-list>
        </div>
      </van-pull-refresh>
      <a
        href="javascript:scroll(0,0)"
        class="backtop"
        tabindex="0"
        role="button"
        aria-label="回到顶部"
        >顶部
      </a>
    </div>
  </div>
</template>


<script>
// 导航
import { Tab, Tabs } from "vant";

import { getCateList, getArticleList } from "@/api/home.js";

export default {
  name: "HomeView",
  components: {
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
  },
  data() {
    return {
      active: 0,
      cate: [],
      list: [],
      articleList: [], //文章列表
      loading: false, //是否正在加载
      finished: false, //是否全部加载完毕
      skip: 0, //从skip开始拿
      limit: 20, //一次拿多少条
      refreshing: false, //是否刷新中
    };
  },
  methods: {
    // 分页
    switchTab() {
      console.log(this.active);
      this.articleList = []; //清空原来数据
      this.skip = 0;
      this.finished = false; //如果不更改会出现bug
      this.getArticle();
    },

    getCate() {
      getCateList().then((res) => {
        console.log(res);
        this.cate = res.data;
        //1. this.cate 所有分类 active  当前选中项索引 this.cate_id=this.cate[this.active]._id
        //2. 等分类接口调用成功后调用
        this.getArticle();

      });
    },

    getArticle(flag) {
      // 检查getArticle是否触发
      // console.log("触发了");

      // 获取内容信息
      let { cate_id, skip, limit } = this;
      getArticleList({
        // id数据
        cate_id,
        skip,
        limit,
      })
        .then((res) => {
          console.log(res);

          //每次拿到的数据都赋值给了articleList
          // 应该做累加的操作  向上滑数据增加
          setTimeout((v) => {
            // 图片压缩
            if (res.data) {
              res.data = res.data.map((v) => {
                v.imageSrc = v.imageSrc.map((v) => {
                  return v + "?imageView2/2/w/115/h/200";
                });
                return v;
              });
            }

            //如果flag存在则是刷新
            if (flag) {
              this.refreshing = false;
              this.articleList = res.data; //如果是刷新把数据替换
            } else {
              this.articleList.push(...res.data); //如果是加载把数据追加
            }
            //每次请求完  做判断 加载完毕 this.finished：true   反之loading：false
            let len = this.articleList.length;
            let count = res.count;

            if (len >= count) {
              this.finished = true;
            } else {
              this.loading = false;
              this.skip = len;
            }
            // this.skip = this.articleList.length; //skip动态变化
          }, 500);
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //下拉刷新
    onRefresh() {
      console.log("刷新了");
      this.skip = 0;
      this.finished = false; //如果不更改会出现bug
      //通过参数 判断getArticle是否是加载动作
      this.getArticle(true); //结束刷新
    },
  },

  computed: {
    // 获取选中分类id
    cate_id() {
      let active_cate = this.cate[this.active];
      // console.log(active_cate);
      if (!active_cate) return "";
      return active_cate._id;
    },
  },
  // 创建后
  created() {
    this.getCate(); //获取分类
  },
  //组件被keep-alive缓存后  多出的两个生命周期钩子
  //激活后  mounted之后
  activated() {
    console.log("激活");
  },
  // 失活后
  deactivated() {
    console.log("失活");
  },

  // 过滤器   时间戳转日期
  filters: {
    timeFilter(times) {
      let time = new Date(times);
      function timeAdd0(str) {
        if (str < 10) {
          str = "0" + str;
        }
        return str;
      }
      let y = time.getFullYear();
      let m = time.getMonth() + 1;
      let d = time.getDate();
      let h = time.getHours();
      let mm = time.getMinutes();
      let s = time.getSeconds();
      return (
        y +
        "-" +
        timeAdd0(m) +
        "-" +
        timeAdd0(d) +
        " " +
        timeAdd0(h) +
        ":" +
        timeAdd0(mm) +
        ":" +
        timeAdd0(s)
      );
    },
  },
};
</script>
<style lang="less" scoped>
// 悬停显示隐藏
.title_hover {
  width: 380px; //设置隐藏显示的最大宽度
  white-space: nowrap; // 设置文字在一行显示，不能换行
  overflow: hidden; // 文字长度超出限定宽度，则隐藏超出的内容
  text-overflow: ellipsis;
}

// 返回顶部
.backtop {
  border-radius: 25px;
  width: 50px;
  height: 40px;
  background-color: #e1dbdb;
  color: #0004ff;
  text-align: center;
  line-height: 40px;
  position: fixed;
  right: 20px;
  bottom: 60px;
}
* {
  list-style: none;
}
.main-article{
  // margin-top: 30px;
  border-bottom:1px solid #adadad ;
}


.main-image{
  display: flex;
}

// .home{
//   background: url(../assets/10.jpg)no-repeat;
  
//   background-attachment: fixed;
//   background-size: cover;
//   background-size: 100% 100%;
// }

.home-header-search {
  width: 260px;
  height: 34px;
  border-radius: 20px;
  background-color: lightgreen;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}

::v-deep .van-nav-bar__title {
  max-width: 75%;
}

::v-deep .van-tabs__line {
  background-color: lightgreen;
}

::v-deep .van-tab {
  border-right: 1px solid #a3a3a3;
  border-bottom: 1px solid #8a8a8a;
}

::v-deep .van-tabs__line {
  bottom: 4vw;
  width: 10.66667vw;
  background-color: lightgreen;
}

.main {
  margin: 0 20px;
  overflow: hidden;
  img {
    max-width: 100%;
  }
}
// 下拉刷新
.doge {
  width: 150px;
  height: 72px;
  margin-top: 8px;
  border-radius: 4px;
}
</style>